package com.albedo.java.web.filter;

import com.albedo.java.common.config.AlbedoProperties;
import com.albedo.java.common.security.SecurityUtil;
import com.albedo.java.util.PublicUtil;
import com.albedo.java.util.spring.SpringContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Filter used to put the CSRF token generated by Spring Security in a cookie for use by AngularJS.
 */
public class PageInitParamFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        AlbedoProperties albedoProperties = SpringContextHolder.getBean(AlbedoProperties.class);
        String basePath =  albedoProperties.getMicroModel() ? "" : PublicUtil.toAppendStr(request.getScheme(), "://", request.getServerName(), ":", request.getServerPort(), request.getContextPath());
        request.setAttribute("basePath", basePath);
        String adminPath = albedoProperties.getAdminPath();
        request.setAttribute("ctx", PublicUtil.toAppendStr(basePath, (albedoProperties.getMicroModel() ? "../" + albedoProperties.getMicorservice() : "") + adminPath));
        request.setAttribute("gatewayModel", albedoProperties.getGatewayModel());
        request.setAttribute("assets", PublicUtil.toAppendStr(basePath, "/statics/assets"));
        request.setAttribute("ctxStatic", PublicUtil.toAppendStr(basePath, "/statics/frame"));
        request.setAttribute("application", albedoProperties.getApplication());
        HttpSession session = request.getSession();
        if (session.getAttribute("moduleList") == null && PublicUtil.isNotEmpty(SecurityUtil.getCurrentUserId())) {
            session.setAttribute("moduleList", SecurityUtil.getModuleList());
        }
        filterChain.doFilter(request, response);
    }
}
